import React, { PureComponent } from 'react';
import { Card, message, Button } from 'antd';
import { getToken } from '@/utils/utils';
import { getMd5 } from '@/utils/utils';
import * as XLSX from 'xlsx/xlsx.mjs';
import { fingerprintFetch } from '@/utils/request'

class ExcelView extends PureComponent<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {};
  }

  componentDidMount () {
    const { onRef } = this.props;
    onRef && onRef(this);
  }

  fecthFile = async (file: any) => {
    const { fileUrl } = file;
    if (!fileUrl) {
      message.error('日志文件缺失或格式不正确，无法预览！');
      return;
    }
    const str = `${window.g.url}/common/download?strUrl=` + fileUrl;
    let md5 = getMd5('strUrl=' + fileUrl);
    const newOptions: any = {};
    newOptions.method = 'GET';
    newOptions.headers = {
      OptAuthorization: `${getToken()}`,
      shaSign: md5,
      'Content-Type': 'application/json;charset=utf-8',
    };
    fingerprintFetch(str, newOptions)
      .then(response => {
        console.log(response);
        if (response.status === 200) {
          return response.blob();
        } else {
          throw response;
        }
      })
      .then(blob => {
        this.loadFile(blob);
      })
      .catch(() => message.error('预览失败111，请稍后在试!'))
  }

  loadFile = (blob: any) => {
    console.log(blob);
    const reader = new FileReader();
    //通过readAsArrayBuffer将blob转换为ArrayBuffer对
    reader.readAsArrayBuffer(blob) // 这里的res.data是blob文件流
    reader.onload = (event: any) => {
      // 读取ArrayBuffer数据变成Uint8Array
      let data = new Uint8Array(event.target.result);
      // 这里的data里面的类型和后面的type类型要对应
      let workbook = XLSX.read(data, { type: "array" });
      let sheetNames = workbook.SheetNames; // 工作表名称
      let worksheet = workbook.Sheets[sheetNames[0]];
      // var excelData = XLSX.utils.sheet_to_json(worksheet); //JSON
      let html = XLSX.utils.sheet_to_html(worksheet);
      const dm = document.getElementById('excel-render') as HTMLElement;
      dm.innerHTML = html
    };
  }

  initView = (file: any) => {
    this.fecthFile(file);
  }

  render() {
    return (
      <div id="excel-render" style={{ width: '100%', height: '100%', inset: '32px 0 0', }}></div>
    )
  }
}
export default ExcelView;
